﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace IGolovkine.ShoutCastRipper.Service.Windows
{
    public partial class RadioRipperWindowsService : ServiceBase
    {
        private StationRipperServiceHost _service;

        public RadioRipperWindowsService()
        {
            try
            {
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(UnhandledException);
                InitializeComponent();
                var config = ServiceConfigurationManager.LoadServiceProperties();
                _service = new StationRipperServiceHost(config);
            }
            catch (Exception ex)
            {
                WriteToEventLog("{0}: {1}", ex.Message, ex.StackTrace);
                throw ex;
            }
        }

        private void UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = (Exception)e.ExceptionObject;
            WriteToEventLog("Unhandled exception {0}: {1}", ex.Message, ex.StackTrace);
        }

        private static void WriteToEventLog(string format, params object[] args)
        {
            string EventSource = typeof(RadioRipperWindowsService).Name;
            string message = string.Format(format, args);
            EventLog.WriteEntry(EventSource, message, EventLogEntryType.Error);
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                _service.StartAll();
            }
            catch (Exception ex)
            {
                WriteToEventLog("{0}: {1}", ex.Message, ex.StackTrace);
                throw ex;
            }
        }

        protected override void OnStop()
        {
            try
            {
                _service.StopAll();
            }
            catch (Exception ex)
            {
                WriteToEventLog("{0}: {1}", ex.Message, ex.StackTrace);
                throw ex;
            }
        }
    }
}
